#include "mainzbar.h"

MainZBar::MainZBar() {
}
// 二值化，阈值
void MainZBar::thresholdImage(QImage &image, int threshold)
{
    // 确保图像是独占的，如果不是独占的，则会进行深拷贝
    if (image.format() != QImage::Format_Grayscale8) {
        image = image.convertToFormat(QImage::Format_Grayscale8);
    } else {
        image.detach();
    }

    // 遍历每个像素
    for (int y = 0; y < image.height(); ++y) {
        for (int x = 0; x < image.width(); ++x) {
            // 获取当前像素的灰度值
            int gray = qGray(image.pixel(x, y));

            // 应用阈值
            if (gray > threshold) {
                image.setPixel(x, y, qRgb(255, 255, 255));  // 设置为白色
            } else {
                image.setPixel(x, y, qRgb(0, 0, 0));  // 设置为黑色
            }
        }
    }
}
// 识别条码和二维码内容（zbar）
QString MainZBar::DecoderInImg(QImage &image)
{
    zbar::ImageScanner scanner;
    //scanner.set_config(zbar::ZBAR_NONE, zbar::ZBAR_CFG_ENABLE, 1);
    scanner.set_config(zbar::ZBAR_NONE, zbar::ZBAR_CFG_X_DENSITY, 1);
    scanner.set_config(zbar::ZBAR_NONE, zbar::ZBAR_CFG_Y_DENSITY, 1);

    // Convert QImage to zbar::Image
    //QImage image = image.convertToFormat(QImage::Format_Grayscale8);
    zbar::Image zbarImage(image.width(), image.height(), "Y800", image.bits(), image.width() * image.height());

    // Scan the image for barcodes
    int n = scanner.scan(zbarImage);

    // Extract results
    QString result;
    for(zbar::Image::SymbolIterator symbol = zbarImage.symbol_begin(); symbol != zbarImage.symbol_end(); ++symbol)
    {
        result = QString::fromStdString(symbol->get_data());
        break; // Assuming there is only one barcode in the image
    }

    return result;
}

// //识别条码和二维码内容（qzxing）
// QString MainZBar::DecoderInImg(QImage &image)
// {
//     QZXing decoder;
//     decoder.setDecoder(QZXing::DecoderFormat_None);
//     decoder.setSourceFilterType(QZXing::SourceFilter_ImageNormal);
//     decoder.setTryHarderBehaviour(QZXing::TryHarderBehaviour_ThoroughScanning | QZXing::TryHarderBehaviour_Rotate);
//     QString result = decoder.decodeImage(image);
//     if(result.isEmpty())
//     {
//         //cv::Mat openImg;
//         //cv::Mat element = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));
//         //morphologyEx(binImg, openImg, cv::MORPH_OPEN, element);
//         //result = decoder.decodeImage(Mat2Image(binImg));
//     }
//     return result;
// }
